import os
from flask import Flask, request, render_template
from werkzeug.serving import make_server
from werkzeug.utils import secure_filename  # 获取上传文件的文件名
from flask_sqlalchemy import SQLAlchemy

# Excel文件的上传和基本信息入库
UPLOAD_FOLDER = r'../Excel/templates'  # 上传路径
ALLOWED_EXTENSIONS = {'xlsx'}  # 允许上传的文件类型

app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
app.config["SQLALCHEMY_DATABASE_URI"] = "mysql://root:521021@localhost:3306/excel"  # 连接数据库
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False
db = SQLAlchemy(app)


class Excel(db.Model):
    __tablename__ = 'exe'
    id = db.Column(db.INTEGER, primary_key=True)
    message = db.Column(db.String(255))


@app.route('/')
def index():
    return render_template('index.html')


def allowed_file(filename):  # 验证上传的文件名是否符合要求，文件名必须带点并且符合允许上传的文件类型要求，两者都满足则返回 true
    return '.' in filename and \
           filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS


@app.route('/upload', methods=['GET', 'POST'])
def upload_file():
    if request.method == 'POST':  # 如果是 POST 请求方式
        file = request.files['file']  # 获取上传的文件
        ro1 = Excel(message=request.form['excel_message'])  # 基本信息入库
        db.session.add(ro1)
        db.session.commit()
        if file and allowed_file(file.filename):  # 如果文件存在并且符合要求则为 true
            filename = secure_filename(file.filename)  # 获取上传文件的文件名
            file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))  # 保存文件
            return '{} upload successed!'.format(filename)  # 返回保存成功的信息
    # 使用 GET 方式请求页面时或是上传文件失败时返回上传文件的表单页面


if __name__ == '__main__':
    server = make_server('127.0.0.1', 5000, app)
    server.serve_forever()
    app.run()
